<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-edit"></i> 报名管理</el-breadcrumb-item>
                <el-breadcrumb-item>报名管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-card shadow="hover">
            <el-button type="primary" @click="handleAdd()" icon="el-icon-plus"
                class="btn_add">添加</el-button>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column label="比赛名称" prop="compName" align="center"/>
                <el-table-column label="参赛者编号" prop="playerID" align="center"/>
                <el-table-column label="运动员姓名" prop="playerName" align="center"/>
                <el-table-column align="center">
                    <template #header>
                        <el-input v-model="search" size="small" placeholder="请输入选手编号" clearable>
                            <template #append>
                                <el-button @click="handleSearch()" icon="el-icon-search">
                                    搜索
                                </el-button>
                            </template>
                        </el-input>
                    </template>
                    <template #default="scope">
                        <el-button size="small" type="danger" icon="el-icon-delete"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 编辑弹出框 -->
            <el-dialog v-model="dialogFormVisible" title="项目" center>
                <el-card shadow="hover">
                    <el-form :model="compForm" :label-width="formLabelWidth">
                        <el-form-item label="比赛名称" >
                            <el-select v-model="compForm.compName" filterable remote 
                                placeholder="请输入关键词" :remote-method="getRecommendCompList"
                                :loading="loading1">
                                <el-option v-for="item in recommendCompList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.label"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="运动员编号-姓名" >
                            <el-select v-model="compForm.IdName" filterable remote 
                                placeholder="请输入关键词" :remote-method="getRecommendPlayerList"
                                :loading="loading2">
                                <el-option v-for="item in recommendPlayerList"
                                    :key="item.value"
                                    :label="item.value+'-'+item.label"
                                    :value="item.value+'-'+item.label"/>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-card>
                <template #footer>
                    <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="danger"  @click="saveAdd()">确认</el-button>
                </template>
            </el-dialog>
        </el-card>
        <!-- 分页 -->
        <el-card>
            <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
                background="true"
                layout="total, prev, pager, next, jumper"
                :total="parseInt(totalNum)" 
                :page-sizes="pageSize" hide-on-single-page
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
    </div>
</template>

<script>
import { computed, reactive, ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from 'vuex';
import { map } from 'lodash';

export default{
    setup(){
        const store = useStore();
        const formLabelWidth = '140px';

        //项目对话框
        const dialogFormVisible = ref(false);
        
        /* 远程搜索比赛 */
        const loading1 = ref(false);
        const remoteCompList = reactive([]);
        //远程获取所有比赛
        const getCompetitionList = ()=>{
            store.dispatch("CompetitionList",{
                PageNum:currentPage.value,
                PageSize: 100,
            })
            .then(res=>{
                if(res.code===200){
                    // console.log("@@@@@",res)
                    remoteCompList.splice(0,remoteCompList.length,...map(res.obj,(item)=>{
                        return {
                            value:item.cname,
                            label:item.cname,
                        }
                    }))
                    // console.log("@@@",remoteCompList)
                }else{
                    console.log("获取所有比赛失败",res.message)
                }
            })
        }
        const recommendCompList = reactive([]);
        const getRecommendCompList = (query)=>{
            console.log("比赛列表为 ",remoteCompList);
            if(query.length>0){
                loading1.value = true;
                setTimeout(() => {
                    loading1.value = false
                    recommendCompList.splice(0,recommendCompList.length,...remoteCompList.filter((item) => {
                        // console.log("item is",item)
                        return item.label.toString().search(query)>-1 ||
                            item.value.toString().search(query)>-1
                    })) 
                    console.log("推荐的比赛列表为 ",recommendCompList)
                }, 200)
            }else{
                recommendCompList.splice(0,recommendCompList.length,...remoteCompList)
            }
        };

        /*
            远程搜索参赛者
        */
        //远程参赛者列表
        const remotePlayerList = reactive([]) 
        //先获取远程所有选手数据
        const getAllPlayerInfo = ()=>{
            store.dispatch("AllPlayerInfo").then((res)=>{
                if(res.code===200){
                    remotePlayerList.splice(0,remotePlayerList.length,...map(res.obj,(item)=>{
                        return {
                            value:item.PId,
                            label:item.Name,
                        }
                    }))
                }else{
                    console.log("获取所有选手数据失败",res.message)
                }
            })
        }
        //远程参赛者搜索
        const recommendPlayerList = reactive([]);
        const loading2 = ref(false);
        
        const getRecommendPlayerList = (query)=>{
            console.log("处理后的远端数据为 ",remotePlayerList)
            if(query.length>0){
                loading2.value = true;
                setTimeout(() => {
                    loading2.value = false
                    recommendPlayerList.splice(0,recommendPlayerList.length,...remotePlayerList.filter((item) => {
                        // console.log("item",item)
                        return item.label.toString().search(query)>-1 ||
                            item.value.toString().search(query)>-1
                    })) 
                    // console.log("推荐的参赛者列表为 ",recommendPlayerList)
                }, 200)
            }else{
                recommendPlayerList.splice(0,recommendPlayerList.length,...remotePlayerList)
            }
        };
        

        //项目表单
        const compForm = reactive({
            compName: '',//比赛名称
            IdName:"",//运动员编号-姓名
        });

        //搜索框
        const search = ref('');
        const handleSearch = ()=>{
            // console.log("搜索内容",search)
            store.dispatch("PLayerEnrollComp",search.value)
            .then((res)=>{
                if(res.code===200){
                    tableData.splice(0, tableData.length,...map(res.obj,(item)=>{
                        return {
                            compName: item.cname,
                            playerID: item.pid,
                            playerName: item.pname,
                        }
                    }))
                    totalNum.value = pageSize.value;
                    console.log("报名列表",tableData);   
                }else{
                    ElMessage({
                        type:"error",
                        message:res.message,
                        center:true,
                    })
                }
            })
            .catch(err=>{
                console.log("报错为",err)
            })
        }
        watch(search,(val)=>{
            if(val===''){
                getPlayerList();
            }
        })

        //处理添加比赛人员
        const handleAdd = () => {
            dialogFormVisible.value = true;
        }

        //提交数据
        const saveAdd = ()=>{
            ElMessageBox.confirm("确定要添加吗","提示",{
                type:"warning",
                center:true,
            }).then(()=>{
                console.log("添加数据为",compForm)
                store.dispatch("EnrollCompetition",{
                    cname:compForm.compName,
                    pid:compForm.IdName.split("-")[0],
                }).then(res=>{
                    if(res==="ok"){
                        ElMessage({
                            type:"success",
                            message:"添加成功",
                            center:true
                        })
                    getPlayerList();
                    }else{
                        ElMessage({
                            type:"error",
                            message:res,
                            center:true
                        })
                    }
                })
                dialogFormVisible.value = false
            }).catch((err)=>{
                console.log("添加报名出现异常",err)
            })
        }

        //处理删除
        const handleDelete = (index, row) => {
            console.log(index, row)
            ElMessageBox.confirm("确定要删除吗","提示",{
                type:"warning",
                center:true,
            }).then(()=>{
                store.dispatch("CancelEnroll",{
                    PId:row.playerID,
                    CName:row.compName,
                }).then(res=>{
                    if(res.code===200){
                        tableData.splice(index, 1);
                        ElMessage({
                            type:"success",
                            message:"删除成功",
                            center:true,
                        });
                        getPlayerList();
                    }else{
                        ElMessage({
                            type:"error",
                            message:"删除失败,请重试",
                            center:true,
                        });
                    }
                }).catch(err=>{
                    console.log("取消报名过程出现异常 ",err);
                })
            })
        }

        //项目列表
        const tableData = reactive([]);
        const getPlayerList = ()=>{
            store.dispatch("CompetitionPlayerListByPage",currentPage.value).then(res=>{
                // console.log("报名列表响应结果",res)
                if(res.code===200){
                    totalNum.value = res.message.split("-")[0];
                    tableData.splice(0, tableData.length,...map(res.obj,(item)=>{
                        return {
                            compName: item.cname,
                            playerID: item.pid,
                            playerName: item.pname,
                        }
                    }))
                }else{
                    ElMessage({
                        type:"error",
                        message:res.message,
                        center:true,
                    })
                }
            })
        }
        

        onMounted(()=>{
            getPlayerList();
            getCompetitionList();
            getAllPlayerInfo();
            
        })

        
        //分页
        let currentPage = ref(1);
        let pageSize = ref(5);
        let totalNum = ref(null);//总条数除以每页显示条数5
        const handleSizeChange = (val) => {
            console.log(`${val} items per page`)
        }
        const handleCurrentChange = (val) => {
            console.log(`current page: ${val}`)
            getPlayerList();
        }
        return {
            compForm,
            dialogFormVisible,
            //远程搜索参赛者
            loading2,
            remotePlayerList,
            recommendPlayerList,
            getRecommendPlayerList,
            //远程搜索项目
            loading1,
            remoteCompList,
            recommendCompList,
            getRecommendCompList,

            formLabelWidth,
            search,
            tableData,

            handleAdd,
            saveAdd,
            handleDelete,
            
            handleSearch,
            //分页
            currentPage,
            pageSize,
            totalNum,
            handleSizeChange,
            handleCurrentChange,
        }
    }
}
</script>

<style scoped>

.btn_add{
    margin: 10px 0px;
    float:right;
}
</style>